<?php
namespace common\components\behaviors;

use common\components\bases\BaseModel;
use yii\db\ActiveRecord;
use yii\base\Behavior;

/**
 * 当所引用的模型数据发生变化触发事件将新的内容缓存到缓存
 * @author: 郭建飞
 * Date: 2015-3-11
 * Time: 11:11
 */

class UpdateCacheBehavior extends Behavior {
	
	public $cacheName;
	
	public $fieldName;


    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'updateCache',
            ActiveRecord::EVENT_AFTER_UPDATE => 'updateCache',
            ActiveRecord::EVENT_AFTER_DELETE => 'updateCache',
			BaseModel::EVENT_AFTER_INSERT => 'afterSave',
            BaseModel::EVENT_AFTER_UPDATE => 'afterSave',
            BaseModel::EVENT_AFTER_DELETE => 'afterDelete',
            \frontend\components\bases\BaseModel::EVENT_AFTER_INSERT => 'updateCache',
            \frontend\components\bases\BaseModel::EVENT_AFTER_UPDATE => 'updateCache',
            \frontend\components\bases\BaseModel::EVENT_AFTER_DELETE => 'updateCache',
        ];
    }

    public function updateCache($event){
        if(\Yii::$app->request->get('site')!=null)\Yii::$app->cacheManage->site=\Yii::$app->request->get('site');
        if($this->fieldName!==null){
            $fileName=$this->fieldName;
            \Yii::$app->cacheManage->fieldName=$this->owner->$fileName;
        }
		if($this->cacheName!==null){
			\Yii::$app->cacheManage->cacheName=$this->cacheName;
            \Yii::$app->cacheManage->UpdateCache();
		}
	}
	
	public function afterSave($event){
        if(\Yii::$app->request->get('site')!=null)\Yii::$app->cacheManage->site=\Yii::$app->request->get('site');
		if($this->cacheName!==null){
			\Yii::$app->cacheManage->cacheName=$this->cacheName;
            \Yii::$app->cacheManage->UpdateCache();
		}
		if($this->fieldName!==null){
			$fileName=$this->fieldName;
            \Yii::$app->cacheManage->cacheName=ucfirst($this->owner->$fileName).'Cache';
            \Yii::$app->cacheManage->UpdateCache();
		}
	}
	
	public function afterDelete($event){
        if(\Yii::$app->request->get('site')!=null)\Yii::$app->cacheManage->site=\Yii::$app->request->get('site');
		if($this->cacheName!==null){
            \Yii::$app->cacheManage->cacheName=$this->cacheName;
            \Yii::$app->cacheManage->UpdateCache();
		}
		if($this->fieldName!==null){
			$fileName=$this->fieldName;
            \Yii::$app->cacheManage->cacheName=ucfirst($this->owner->$fileName).'Cache';
            \Yii::$app->cacheManage->UpdateCache();
		}
	}

}

?>